package com.sev.jfa.common;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.jfinal.plugin.activerecord.IContainerFactory;

/**
 * 数据库字段转换为驼峰格式
 * 默认按字段中的_下划线处理
 * @author kool.zhao
 *
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public class CaseCamelContainerFactory implements IContainerFactory {

	public static char toCamelCase='_'; 
	
	public CaseCamelContainerFactory(){};
	
	public CaseCamelContainerFactory(char toCamelCase){
		CaseCamelContainerFactory.toCamelCase = toCamelCase;
	};
	
	public Map<String, Object> getAttrsMap() {
		return new CaseInsensitiveMap();
	}
	
	public Map<String, Object> getColumnsMap() {
		return new CaseInsensitiveMap();
	}
	
	public Set<String> getModifyFlagSet() {
		return new CaseInsensitiveSet();
	}
	
	private static Object convertCase(Object key) {
		if (key instanceof String){
			return underlineToCamel((String) key);
		}
		return key;
	}
	
   public static String underlineToCamel(String param){  
       if (param==null||"".equals(param.trim())){  
           return "";  
       }  
       param = param.toLowerCase();
       int len=param.length();  
       StringBuilder sb=new StringBuilder(len);  
       for (int i = 0; i < len; i++) {  
           char c=param.charAt(i);  
           if (c==toCamelCase){  
              if (++i<len){  
                  sb.append(Character.toUpperCase(param.charAt(i)));  
              }  
           }else{  
               sb.append(c);  
           }  
       }  
       return sb.toString();  
   } 
	
	public static class CaseInsensitiveSet extends HashSet {
		
		private static final long serialVersionUID = 102410961064096233L;
		
		public boolean add(Object e) {
			return super.add(convertCase(e));
		}
		
		public boolean remove(Object e) {
			return super.remove(convertCase(e));
		}
		
		public boolean contains(Object e) {
			return super.contains(convertCase(e));
		}
		
		public boolean addAll(Collection c) {
			boolean modified = false;
			for (Object o : c)
				if (super.add(convertCase(o)))
					modified = true;
			return modified;
		}
	}
	
	public static class CaseInsensitiveMap extends HashMap {
		
		private static final long serialVersionUID = 6843981594457576677L;
		
		public Object get(Object key) {
			return super.get(convertCase(key));
		}
		
		public boolean containsKey(Object key) {
			return super.containsKey(convertCase(key));
		}
		
		public Object put(Object key, Object value) {
			return super.put(convertCase(key), value);
		}
		
		public void putAll(Map m) {
			for (Map.Entry e : (Set<Map.Entry>)(m.entrySet()))
				super.put(convertCase(e.getKey()), e.getValue());
		}
		
		public Object remove(Object key) {
			return super.remove(convertCase(key));
		}
	}


}
